package com.huluobo.base.mvvm

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.SPUtils
import com.huluobo.base.bean.Res
import com.huluobo.base.net.Const
import kotlinx.coroutines.launch
import java.lang.Exception

/**
 *  Created by LC on 2024/8/8.
 */
abstract class BaseViewModel : ViewModel() {
    val onFailed by lazy { MutableLiveData<Throwable>() }

    fun <D> executeNetRequest(
        s: suspend () -> Res<D>,
        success: (String) -> Unit,
        failed: (Throwable) -> Unit = onFailed::postValue,
        okCode: Int = 200
    ) {
        viewModelScope.launch {
            try {
                val res = s.invoke()
                SPUtils.getInstance().put(Const.PARAM_HOME, res.home)
                if (res.statuesCode.toInt() == okCode) {
                    success(res.values)
                } else {
                    failed(RuntimeException(res.msg))
                }
            } catch (e: Exception) {
                failed(e)
            }
        }
    }
}